package com.jzlin.funhub.admin.service.article;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzlin.funhub.admin.mapper.ArticleTagsRefMapper;
import com.jzlin.funhub.admin.model.dto.ArticleTagDTO;
import com.jzlin.funhub.admin.model.dto.ArticleTagGroupDTO;
import com.jzlin.funhub.admin.model.entity.ArticleTag;
import com.jzlin.funhub.admin.model.entity.ArticleTagsRef;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文章标签关联表 服务实现类
 * </p>
 *
 * @author jzlin
 * @since 2025-09-04
 */
@Service
public class ArticleTagsRefService extends ServiceImpl<ArticleTagsRefMapper, ArticleTagsRef> {

    @Autowired
    private ArticleTagService articleTagService;

    /**
     * 绑定文章与标签
     * @param articleId 文章id
     * @param tags 标签列表
     */
    @Transactional
    public void bindTagsForArticle(Long articleId, List<String> tags) {
        //清除文章标签
        deleteTagsForArticle(articleId);
        //获取标签
        List<ArticleTag> articleTags = articleTagService.getTagsByName(tags);

        List<ArticleTagsRef> articleTagsRefs = new ArrayList<>();
        for (ArticleTag tag : articleTags) {
            ArticleTagsRef articleTagsRef = new ArticleTagsRef();
            articleTagsRef.setArticleId(articleId);
            articleTagsRef.setTagId(tag.getId());

            articleTagsRefs.add(articleTagsRef);
        }
        this.saveBatch(articleTagsRefs);
    }

    /**
     * 删除文章所有标签
     * @param articleId 文章id
     */
    public void deleteTagsForArticle(Long articleId) {
        this.remove(new QueryWrapper<ArticleTagsRef>().eq("article_id", articleId));
    }

    /**
     * 列出文章所有标签
     * @param articleId
     * @return
     */
    public List<ArticleTagDTO> listTagsByArticleId(Long articleId) {
        return this.baseMapper.listTagsByArticleId(articleId);
    }

    /**
     * 列出所有标签和文章数量
     * @return
     */
    public List<ArticleTagGroupDTO> countArticleByTag() {
        return this.baseMapper.countArticleByTag();
    }
}
